import { _decorator, Component, error, instantiate, Label, log, Node, Prefab } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('EnemyManager')
export class EnemyManager extends Component {

    private static instance:EnemyManager = null;

    //敌人列表
    enemies:Node[] = [];

    @property(Prefab)
    enemyPrefab:Prefab = null;

    @property(Node)
    gameManager:Node = null;

    @property(Label)
    enemiesCountLabel:Label = null;

    timer:number = 0;

    enemiesCount:number = 0;

    public isGaming:boolean = true;
    

    //获取实例
    public static getInstance():EnemyManager{
        return this.instance;
    }

    protected onLoad(): void {
        EnemyManager.instance = this;
    }

    start() {
        this.node.on("addEnemy",this.addEnemy,this);
        this.node.on("removeEnemy",this.removeEnemy,this);

        log("Round:"+this.enemiesCount.toString()+"/3");
        this.enemiesCountLabel.string = "Round:"+this.enemiesCount.toString()+"/3"; 
    }

    //添加敌人
    addEnemy(enemy:Node){
        this.enemies.push(enemy);
    }


    //移除敌人
    removeEnemy(enemy:Node){
        this.enemies.splice(this.enemies.indexOf(enemy),1);
    }


    update(deltaTime: number) {

        if(!this.isGaming || this.enemiesCount >= 3){
            log("所有敌人生成完毕");
            return;
        }

        //写一个计时器，3秒刷新一次
        this.timer -= deltaTime;
        if(this.timer <= 0){

            this.enemiesCount++;
            this.enemiesCountLabel.string = "Round:"+this.enemiesCount.toString()+"/3"; 
            for(var i = 0;i < 5;i++){
                this.createEnemy();
            }

            this.timer = 20;
        }
    }


    //创建敌人
    createEnemy(){
        var random = Math.floor(Math.random() * (3000 - 500 + 1)) + 500;
        setTimeout(()=>{
            var enemy = instantiate(this.enemyPrefab);
            enemy.setParent(this.node);
            enemy.setPosition(0,0,0);
            this.addEnemy(enemy);
        },random);

        this.gameManager.emit("createEnemy",this.node);
    }


}


